package com.groot.medical.servlet;


import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.google.gson.Gson;
import com.groot.common.controller.BaseServletController;
import com.groot.common.util.ExcelUtils;

import com.groot.common.util.TicketUtil;
import com.groot.medical.entity.AdministrativeArea;

import com.groot.medical.entity.Menu;
import com.groot.medical.entity.PageBean;
import com.groot.medical.entity.Pay;
import com.groot.medical.entity.PaySetting;
import com.groot.medical.entity.PersonalFiles;
import com.groot.medical.entity.SysUser;
import com.groot.medical.service.AdministrativeAreaService;
import com.groot.medical.service.AdministrativeAreaServiceImpl;
import com.groot.medical.service.FamilyArchivesService;
import com.groot.medical.service.FamilyArchivesServiceImpl;
import com.groot.medical.service.PayService;
import com.groot.medical.service.PayServiceImpl;
import com.groot.medical.service.PaySettingService;
import com.groot.medical.service.PaySettingServiceImpl;
import com.groot.medical.service.PersonalFileService;
import com.groot.medical.service.PersonalFileServiceImpl;
import com.itextpdf.text.pdf.codec.Base64.OutputStream;

@WebServlet("/sys/pay.do")
public class PayController extends BaseServletController{
	private static final long serialVersionUID = 1L;
	private static Logger LOGGER = Logger.getLogger(PayController.class);
	private FamilyArchivesService familyArchivesService = new FamilyArchivesServiceImpl();
	private AdministrativeAreaService areaService = new AdministrativeAreaServiceImpl();
	private PaySettingService paySettingService = new PaySettingServiceImpl();
	private PayService payService = new PayServiceImpl();
	private PersonalFileService personalFileService = new PersonalFileServiceImpl();
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOGGER.info("this is @WebServlet(\"/index.do\").execute()");
		return null;
	}
	
	
	/**
	 * 查询家庭和户主信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findFamilyInfoList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tgId = request.getParameter("tgId");
		String holdername = request.getParameter("holdername");
		String townCode = request.getParameter("townCode");
		int pageNum = Integer.valueOf(request.getParameter("pageNum"));
		List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
		List<Menu> result = new ArrayList<Menu>();
		/*根据页面传过来的id与该用户所有权限的上一级id比较
		 * 若该权限的上一级传过来的id相同则存入新集合
		 */
		for(Menu menu: menus){
			if(menu.getMenuPid().equals(tgId)){
				result.add(menu);
			}
		}
		
		Gson gson = new Gson();
		request.setAttribute("resultMenus", gson.toJson(result));
		request.setAttribute("tgId", tgId);
		
		townCode=townCode==null || "".equals(townCode)? "" : townCode;
		holdername=holdername==null || "".equals(holdername)? "" : holdername;
		String year="&townCode="+townCode+"&holdername="+holdername;
		request.setAttribute("year", year);
		//获取当前时间
		Date now = new Date();
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String nowTime = time.format(now);
		
		SimpleDateFormat years = new SimpleDateFormat("yyyy");//设置日期格式
		String currentYear = years.format(now);
		//检查是否设置当前金额以及是否在缴费时间段
		PaySetting paySetting=paySettingService.checkInPayTime(currentYear,nowTime);
		if(paySetting.getPayMonry()==null || paySetting.getPayMonry().equals("")){
			request.setAttribute("flag", "<script type='text/javascript'>alert('当前时间不在缴费时间段内，');</script>");
			return findPayList(request,response);
		}else{
			System.out.println("有吗：：："+paySetting);
			int pageSize = 5;
			PageBean areaPage = familyArchivesService.findByPageAndLike(pageNum, pageSize,holdername,townCode);
			//查询县级的信息
			List<AdministrativeArea> towns=areaService.findAllTownInfo();
			System.out.println("areaPage:"+areaPage);
			request.setAttribute("towns", towns);
			request.setAttribute("areaPage", areaPage);
			request.setAttribute("tgId", tgId);
			return "/WEB-INF/page/pay/family_list.jsp";
		}
		
	}
	
	/**
	 * 查询参合缴费登记列表信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findPayList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接受页面传来的模糊查询的条件
		String currentYear = request.getParameter("currentYear");
		String townCode = request.getParameter("towns");
		String starttime = request.getParameter("starttime");
		String endtime = request.getParameter("endtime");
		String holdername = request.getParameter("holdername");
		String tgId = request.getParameter("tgId");
		int pageNum = Integer.valueOf(request.getParameter("pageNum"));
		List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
		List<Menu> result = new ArrayList<Menu>();
		/*
		 * 根据页面传过来的id与该用户所有权限的上一级id比较
		 * 若该权限的上一级传过来的id相同则存入新集合
		 */
		for(Menu menu: menus){
			if(menu.getMenuPid().equals(tgId)){
				result.add(menu);
			}
		}
		Gson gson = new Gson();
		request.setAttribute("resultMenus", gson.toJson(result));
		request.setAttribute("tgId", tgId);
		
		currentYear=currentYear==null || "".equals(currentYear)? "" : currentYear;
		townCode=townCode==null || "".equals(townCode)? "" : townCode;
		holdername=holdername==null || "".equals(holdername)? "" : holdername;
		String year="&currentYear="+currentYear+"&towns="+townCode+"&holdername="+holdername;
		request.setAttribute("year", year);
		int pageSize = 5;
		//生成时间
		Date now = new Date();
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String nowTime = time.format(now); 
		request.setAttribute("nowTime", nowTime);
		System.out.println(nowTime);
		
		//查询县级的信息
		List<AdministrativeArea> towns=areaService.findAllTownInfo();
		request.setAttribute("towns", towns);
		//模糊查询列表信息（条件有：所在年份，起始、结束时间，户主姓名，所在乡镇）
		PageBean areaPage = payService.findByPage(pageNum, pageSize,currentYear,townCode,holdername);
		request.setAttribute("areaPage", areaPage);
		
		
		return "/WEB-INF/page/pay/pay_list.jsp";
	}
	/**
	 * 判断该年度家庭是否存在为参合人员
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String checkNoPayPerson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String familyCode = request.getParameter("familyCode");
		String pageNum = request.getParameter("pageNum");
		String tgId = request.getParameter("tgId");
		//生成时间
		Date now = new Date();
		SimpleDateFormat time = new SimpleDateFormat("yyyy");//设置日期格式
		String nowTime = time.format(now); 
		System.out.println(nowTime);
		//查询本年度的缴费标准
		String money =paySettingService.findMoneyByCurrentYear(nowTime);
		//查询出该家庭的所有成员信息
		List<PersonalFiles> familys = familyArchivesService.findFamilyAllPersonByFamilyCode(familyCode);
		
		//查询参合缴费表中的所有信息
		List<Pay> payList = payService.findPayInfoByFamilyCodeAndYear(familyCode,nowTime);
		System.out.println(payList);
		if(payList==null ){
			payList=new ArrayList<>();
		}
		//遍历比对(核心代码价值2个亿)
		for(int j=0;j<payList.size(); j++){
		  for(int i=0;i<familys.size();i++){
			if(familys.get(i).getIdcardNumber().equals(payList.get(j).getIdcardCode())){
				familys.remove(i);
				System.out.println(familys.toString());
				break;
			}
		  }
		}
		System.out.println(familys.toString());	
		System.out.println("家庭："+familys.size());
		System.out.println("参合："+payList.size());
		if(familys.size()==0){
			request.setAttribute("pageNum", pageNum);
			request.setAttribute("tgId", tgId);
			request.setAttribute("flag", "<script type='text/javascript'>alert('该家庭今年全部参合！');</script>");
			return findFamilyInfoList(request,response);
		}else{
			request.setAttribute("familys", familys);
			request.setAttribute("payList", payList);
			request.setAttribute("tgId", tgId);
			request.setAttribute("money", money);
			
			return "/WEB-INF/page/pay/pay_money.jsp";
		}
			
		
	}
	/**
	 * 执行缴费
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String PayMoneyforPerson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取身份证号
		String [] ids = request.getParameterValues("ids");
		int priceNumber = ids.length;
		//获取单价
		String price = request.getParameter("price");
		//计算总金额
		int allPrice=priceNumber*Integer.parseInt(price);
		//生成时间当前年份
		Date now = new Date();
		SimpleDateFormat time = new SimpleDateFormat("yyyy");//设置日期格式
		String year = time.format(now);
		//凭证单号
		String ticket = TicketUtil.getDefaultFapiao();
		//设置当前时间
		SimpleDateFormat localtime = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String nowTime = localtime.format(now);
		//session取值
		SysUser user=(SysUser) request.getSession().getAttribute("sysUser");
		List<Pay> payPerson  = new ArrayList<>();
		for(int i = 0;i<ids.length;i++){
			//根据身份证号查询用户信息
			System.out.println(ids[i]);
			PersonalFiles person=personalFileService.findPersonInfoById(ids[i]);
			Pay pay = new Pay();
			pay.setFamilyCode(person.getFamilyCode());
			pay.setIdcardCode(person.getIdcardNumber());
			pay.setFarmingCardCord(person.getFarmingcardCode());
			pay.setCurretYear(year);
			pay.setPayMoney(price);
			pay.setName(person.getName());
			pay.setPayTime(new Date());
			pay.setOperater(user.getUsername());
			pay.setVoucherId(ticket);
			System.out.println(pay);
			payPerson.add(pay);
		}
		//执行参合缴费操作
		payService.payMoneyForPerson(payPerson);
		int length = payPerson.size()+2;
		System.out.println("长度是："+length);
		request.setAttribute("length", length);
		request.setAttribute("payPerson", payPerson);
		request.setAttribute("allPrice", allPrice);
		request.setAttribute("ticket", ticket);
		request.setAttribute("nowTime", nowTime);
		//提示是否打印票据
		return "/WEB-INF/page/pay/pay_print_bill.jsp";
		/*return findPayList(request,response);*/
	}
	
	public String test(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		return "/WEB-INF/page/pay/pay_print_bill.jsp";
	}
	/**
	 * 导出excel表格
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String outExcelInFo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//查询所有的
		String currentYear = request.getParameter("currentYear");
		String townCode = request.getParameter("towns");
		String starttime = request.getParameter("starttime");
		String endtime = request.getParameter("endtime");
		String holdername = request.getParameter("holdername");
		String tgId = request.getParameter("tgId");
		System.out.println("年份："+currentYear);
		System.out.println("镇："+townCode);
		System.out.println("名字："+holdername);	
		
		response.reset(); // 清除buffer缓存
		Date date =new Date();
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
		String name="缴费登记记录";
		String time =sdf.format(date);
		response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(name, "UTF-8")+""+ time +".xlsx");
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		XSSFWorkbook workbook = null;
		//根据查询条件查询对应信息
		List<Pay> paylists=payService.findPayInfoByCondition(currentYear,townCode,holdername);
		List<Pay> payList=payService.findAllPayInfo();
		try {
			workbook = ExcelUtils.exportContacts(paylists);
		} catch (IllegalArgumentException | IllegalAccessException | ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		ServletOutputStream output;
		try {
		output = response.getOutputStream();
		BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
		bufferedOutPut.flush();
		workbook.write(bufferedOutPut);
		bufferedOutPut.close();
		} catch (Exception e) {
		e.printStackTrace();
		}
		return null;
	}
	
	
}
